package com.swz.dcrm.ui.base;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;

import androidx.annotation.DrawableRes;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.billy.android.loading.Gloading;
import com.bumptech.glide.Glide;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.swz.dcrm.R;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.digger.AppComponent;
import com.swz.dcrm.digger.AppModule;
import com.swz.dcrm.digger.DaggerAppComponent;
import com.swz.dcrm.ui.viewmodel.MainViewModel;
import com.swz.dcrm.wrapper.EmptyWrapper;

import butterknife.ButterKnife;
import qiu.niorgai.StatusBarCompat;

/**
 * A simple {@link Fragment} subclass.
 */
public abstract class BaseFragment extends Fragment {

    private View view;
    protected Gloading.Holder mHolder;
    private boolean isNeedPadding;
    public static final String TAG=BaseFragment.class.getName();

    private Toast mToast;
    public BaseFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        if(view==null){
            view =inflater.inflate(layoutId(), container, false);
            if (mHolder == null) {
                //bind status view to activity root view by default

                mHolder = Gloading.getDefault().wrap(view).withRetry(() -> {
                    mHolder.showLoading();
                    onLoadRetry();
                });
            }
            ButterKnife.bind(this,view);

            isNeedPadding=initView();
            if(isNeedPadding){
                view.setPadding(0,getStatusBarHeight(getContext()),0,0);
            }

        }

        if(mHolder.getWrapper().getParent()!=null){
            //当container为viewpager的时候 不能直接返回mHolder.getWrapper()，因为第二次回退的时候会调用这个方法，
            // 因为viewpager会缓存 所以不能重复addView
            if(mHolder.getWrapper().getParent() instanceof ViewPager){
                ViewPager viewPager= (ViewPager) mHolder.getWrapper().getParent();
                viewPager.removeView(mHolder.getWrapper());
            }else {
              ViewGroup viewGroup= (ViewGroup) mHolder.getWrapper().getParent();
              viewGroup.removeView(mHolder.getWrapper());
            }
        }
        mHolder.getWrapper().setTag(view.getTag());
        return mHolder.getWrapper();
    }
    public <T extends  Fragment> AppComponent getDigger(){
        return DaggerAppComponent.builder().appModule(new AppModule(getActivity()))
                .build();
    }


    public void changeStatusBarColor(boolean isWhite){
        if(isWhite){
            StatusBarCompat.setStatusBarColor(getActivity(),getResources().getColor(R.color.white));
        }else {
            StatusBarCompat.setStatusBarColor(getActivity(),getResources().getColor(R.color.bg));
        }
        StatusBarCompat.translucentStatusBar(getActivity(), true);
        View decorView = getActivity().getWindow().getDecorView();
        decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

    }
    public   int getStatusBarHeight(Context context) {
        int result = 0;
        int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resId > 0) {
            result = context.getResources().getDimensionPixelOffset(resId);
        }
        return result;
    }

    public EmptyWrapper getEmptyWrapper(RecyclerView.Adapter baseAdapter, @DrawableRes int pic){
        EmptyWrapper mEmptyWrapper = new EmptyWrapper(baseAdapter);
        ImageView imageView=new ImageView(getContext());
        imageView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        Glide.with(getContext())
                .load(pic)
                .into(imageView);
        mEmptyWrapper.setEmptyView(imageView);

        return mEmptyWrapper;
    }

    public void go(MainViewModel mainViewModel, int ResId,Bundle bundle){
        if(mainViewModel!=null){
            mainViewModel.getShowTab().setValue(false);
        }
        if(bundle!=null){
            NavHostFragment.findNavController(this).navigate( ResId,bundle);
        }else {
            NavHostFragment.findNavController(this).navigate( ResId);
        }
    }

    public TimePickerView.Builder getTimePickerView(TimePickerView.OnTimeSelectListener onTimeSelectListener){
       return new TimePickerView.Builder(getContext(), onTimeSelectListener).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText(getString(R.string.cancel))
                .setSubmitText(getString(R.string.sure))
                .setContentSize(14)//滚轮文字大小
                .setTextColorCenter(getResources().getColor(R.color.black_2f3234))
                .isCyclic(true)//是否循环滚动
                .setSubmitColor(getResources().getColor(R.color.black_2f3234))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.black_2f3234))//取消按钮文字颜色
////                .setRangDate(startDate,endDate)//起始终止年月日设定
                //.setLabel("年","月","日","","","")//默认设置为年月日时分秒
                .isCenterLabel(false)  ;//是否只显示中间选中项的label文字，false则每项item全部都带有label。
    }


    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
    public boolean isWifiConnected(Context context) {
        if (context != null) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mWiFiNetworkInfo != null) {
            return mWiFiNetworkInfo.isAvailable();
        }
    }
        return false;
    }

    @Override
    public void onDestroyView() {
      //  mHolder.showLoadSuccess();
        super.onDestroyView();
    }
    public void showToast(String s){
        if (mToast == null) {

            mToast= Toast.makeText(getContext(),s,Toast.LENGTH_SHORT);
            mToast.setGravity(Gravity.CENTER,0,0);
        } else {

            mToast.setText(s);
        }
        mToast.show();

    }
    NormalDialog normalDialog;
    public void showNormalDialog(boolean isTitleShow,String title, String content, OnBtnClickL sure,OnBtnClickL cancel){
        BounceTopEnter mBasIn = new BounceTopEnter();
        SlideBottomExit mBasOut = new SlideBottomExit();
        normalDialog = new NormalDialog(getContext());
        normalDialog.content(content)
                .title(title)
                .style(NormalDialog.STYLE_TWO)
                .showAnim(mBasIn)
                .cornerRadius(8)
                .titleTextColor(getResources().getColor(R.color.blue_0f6eff))
                .titleTextSize(16)
                .isTitleShow(isTitleShow)
                .dismissAnim(mBasOut)
                .setOnBtnClickL(cancel,sure);
        normalDialog.show();
    }
    public void dismissDialog(){
        if(normalDialog!=null){
            normalDialog.dismiss();
        }
    }
    public abstract void onLoadRetry();
    public abstract int layoutId();
    public abstract boolean initView();
}
